package com.lgl.mes.common.util.org.easy.excel.aop.cell.inner;

import org.apache.commons.lang3.StringUtils;
import com.lgl.mes.common.util.org.easy.excel.aop.cell.CellInterceptorAdapter;
import com.lgl.mes.common.util.org.easy.excel.aop.cell.CellJoinPoint;
import com.lgl.mes.common.util.org.easy.excel.config.FieldValue;
import com.lgl.mes.common.util.org.easy.excel.exception.ExcelException;

/**
 * 处理format标签
 * @author lisuo
 *
 */
public class FormatCellInterceptor extends CellInterceptorAdapter {

	@Override
	public boolean supports(CellJoinPoint joinPoint) {
		return joinPoint.getFieldValue().getFormat() != null && joinPoint.getValue()!=null;
	}

	@Override
	public Object executeImport(CellJoinPoint joinPoint) throws ExcelException {
		return resolverExpression(joinPoint, true);
	}

	@Override
	public Object executeExport(CellJoinPoint joinPoint) throws ExcelException {
		return resolverExpression(joinPoint, false);
	}

	private String resolverExpression(CellJoinPoint joinPoint, boolean isImport) {
		FieldValue fieldValue = joinPoint.getFieldValue();
		String format = fieldValue.getFormat();
		//toString 避免其他类型equals返回false
		Object value = joinPoint.getValue().toString();
		try {
			String[] expressions = StringUtils.split(format, ",");
			for (String expression : expressions) {
				String[] val = StringUtils.split(expression, ":");
				String v1 = val[0];
				String v2 = val[1];
				if (isImport) {
					if (value.equals(v2)) {
						return v1;
					}
				} else {
					if (value.equals(v1)) {
						return v2;
					}
				}
			}
		} catch (Exception e) {
			throw newExcelDataException("表达式:[" + format + "]错误,正确的格式应该以[,]号分割,[:]号取值", joinPoint);
		}
		throw newExcelDataException("[" + value + "]取值错误", joinPoint);
	}

}
